from .plugin import Plugin
from ..signals import SIGNALS
from ..termination import TERMINATION


class CheckOptimality(Plugin):
    """
    This plugin activates every time the gap changes. If the gap becomes zero (within a given
    'tolerance'), the solver is interrupted because the optimal solution has been found.
    """
    signal_map = {SIGNALS.GAP_CHANGED: "check"}
    tolerance = 1e-9

    def check(self, listener):
        if self.solver.gap < self.tolerance:
            self.solver.termination = TERMINATION.OPTIMAL
